﻿using Mengsk.ERP.Database;
using Mengsk.ERP.Orders;
using Mengsk.ERP.Orders.TDOrderInterfaces;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ERP.App.Orders
{
    /// <summary>
    /// Interaction logic for OrderDeliveryImport.xaml
    /// </summary>
    public partial class OrderDeliveryImport : UserControl, IUIPlugin
    {
        private System.Collections.ObjectModel.ObservableCollection<OrderDeliveryViewModel> items = new System.Collections.ObjectModel.ObservableCollection<OrderDeliveryViewModel>();
        private bool updatePPCod = false;

        public string Title
        {
            get { return "打印单号导入"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        public OrderDeliveryImport()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.dgvItems.ItemsSource = items;
        }

        private string ParseDeliveryCompany(string printDeliveryCompany)
        {
            if (printDeliveryCompany.Contains("圆通"))
            {
                return "圆通速递";
            }

            if (printDeliveryCompany.Contains("EMS"))
            {
                return "邮政EMS";
            }

            if (printDeliveryCompany.Contains("宅急送"))
            {
                return "宅急送";
            }

            if (printDeliveryCompany.Contains("小包"))
            {
                return "邮政小包";
            }

            if (printDeliveryCompany.Contains("天天"))
            {
                return "天天快递";
            }

            if (printDeliveryCompany.Contains("中通"))
            {
                return "中通快递";
            }

            throw new Exception("未识别的快递公司");
        }


        private void btnImport_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.updatePPCod = this.chkUpdatePPCod.IsChecked.Value;
                if (this.items.Count < 1)
                {
                    MessageBox.Show("没有数据导入");
                    return;
                }

                foreach (var item in this.items)
                {
                    item.Background = null;
                    item.State = "";
                }

                App.DoEvents();

                foreach (var item in this.items)
                {
                    item.Background = Brushes.Yellow;
                    item.State = "导入中";
                    App.DoEvents();
                    try
                    {
                        Order[] orders = OrderManager.Instance.GetOrdersByPopId(item.Id);
                        if (orders == null || orders.Length < 1)
                        {
                            item.State = "未找到订单";
                            item.Background = Brushes.Red;
                            continue;
                        }
                        else if (orders.Length > 1)
                        {
                            item.State = "找到多个订单";
                            item.Background = Brushes.Red;
                            continue;
                        }
                        Order or = orders[0];
                        if (this.updatePPCod && or.Type == OrderType.TRADE0FF)
                        {
                            Order order = TDOrderInterfaceBase.GetOrder(item.Id, DateTime.Now.AddDays(-30), DateTime.Now);
                            if (order == null)
                            {
                                item.State = "下载订单失败";
                                item.Background = Brushes.Red;
                                continue;
                            }
                            else
                            {
                                or.PPCOD = order.PPCOD;
                            }
                        }
                        or.LastUpdateTimeErp = DateTime.Now;
                        or.Comment = "导入物流信息";
                        or.DeliveryCompany = item.DeliveryCompany;
                        or.DeliveryNumber = item.DeliveryNumber;
                        DBHelper.Instance.Update("", "Order", "POPID='" + item.Id + "'", null, or, true, "DeliveryCompany", "DeliveryNumber", "PPCOD", "LastUpdateTimeErp", "Comment");
                        item.Background = null;
                        item.State = "已导入";
                        this.dgvItems.ScrollIntoView(item);
                        App.DoEvents();
                    }
                    catch (Exception ex)
                    {
                        item.State = ex.Message;
                        item.Background = Brushes.Red;
                        Debug.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
                    }
                }
                MessageBox.Show("导入完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
                ofd.Multiselect = true;
                bool? ret = ofd.ShowDialog();
                if (ret == null || ret.Value == false)
                {
                    return;
                }
                List<string[]> lines = new List<string[]>();
                foreach (string file in ofd.FileNames)
                {
                    Debug.WriteLine("正在解析文件:" + file);
                    var tempLines = CSV.ReadFile(file, Encoding.Default);
                    if (tempLines.Length <= 0)
                    {
                        MessageBox.Show(file, "文件中不包含任何内容");
                    }
                    else
                    {
                        for (int i = 0; i < tempLines.Length; i++)
                        {
                            if (lines.Count > 0 && i == 0)
                            {
                                continue;
                            }
                            lines.Add(tempLines[i]);
                        }
                    }
                }

                if (lines.Count < 1)
                {
                    return;
                }

                List<string> header = lines[0].ToList();
                int iId = header.IndexOf("订单号");
                int iShop = header.IndexOf("卖出店铺");
                int iDeliveryCompany = header.IndexOf("快递");
                int iDeliveryNumber = header.IndexOf("快递单号");
                int iOrderTime = header.IndexOf("日期");
                int iPrint = header.IndexOf("打印时间");
                int iColor = header.IndexOf("颜色");
                int iSize = header.IndexOf("尺码");
                int iCount = header.IndexOf("产品数量");
                int iVendorNumber = header.IndexOf("二级型号");
                int iAddress = header.IndexOf("地址");

                if (iId < 0 || iShop < 0 || iDeliveryCompany < 0 || iDeliveryNumber < 0 || iOrderTime < 0 || iPrint < 0 || iColor < 0 || iSize < 0 || iCount < 0 || iVendorNumber < 0 || iAddress < 0)
                {
                    MessageBox.Show("格式不正确");
                    return;
                }
                for (int i = 1; i < lines.Count; i++)
                {
                    OrderDeliveryViewModel vm = new OrderDeliveryViewModel
                    {
                        Address = lines[i][iAddress],
                        PrintDeliveryCompany = lines[i][iDeliveryCompany],
                        DeliveryCompany = ParseDeliveryCompany(lines[i][iDeliveryCompany]),
                        DeliveryNumber = lines[i][iDeliveryNumber],
                        GoodsInfo = lines[i][iVendorNumber] + " " + lines[i][iColor] + " " + lines[i][iSize] + " " + lines[i][iCount],
                        Id = lines[i][iId],
                        OrderTime = DateTime.Parse(lines[i][iOrderTime]),
                        PrintTime = DateTime.Parse(lines[i][iPrint]),
                        Shop = lines[i][iShop]
                    };

                    vm.Id = vm.Id.Substring(0, vm.Id.Length - 2);

                    if (this.items.FirstOrDefault(obj => obj.Id == vm.Id) == null)
                    {
                        this.items.Add(vm);
                    }
                    else
                    {
                        Debug.WriteLine("检测到重复的ID:" + vm.Id + "  ,  快递模板:" + vm.PrintDeliveryCompany);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.tbTotalCount.Text = "共:" + this.items.Count + "条数据";
            }
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("是否清空", "警告", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
            {
                return;
            }
            this.items.Clear();
        }
    }
}
